using Coldairarrow.Util;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;

namespace Coldairarrow.Util.Others
{
    public class PostRequestHelper : ITransientDependency
    {
        private readonly IHttpClientFactory _clientFactory;
        private ILogger<PostRequestHelper> _logger;
        private readonly IDistributedCache _cache;
        private readonly string key = "AccessToken_"+ ConfigHelper.Configuration.GetSection("SyncDataBasicAuth").GetValue<string>("username");
        public PostRequestHelper(IHttpClientFactory clientFactory, ILogger<PostRequestHelper> logger, IDistributedCache cache)
        {
            _clientFactory = clientFactory;

            _logger = logger;
            _cache = cache;
        }

        public async Task<AccessToken> GetAccessToken()
        {

            string appCode = ConfigurationUtil.GetSection("SyncDataBasicAuth:username");
            string appSecret = ConfigurationUtil.GetSection("SyncDataBasicAuth:password");
            string url = ConfigurationUtil.GetSection("MainAPI:AccessToken");
            url = string.Format(url, appCode, appSecret);
            var client = _clientFactory.CreateClient();
            string msg;
            try
            {

                var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
                var response = await client.SendAsync(request);
                response.EnsureSuccessStatusCode();
                var responseStream = await response.Content.ReadAsStreamAsync();
                AjaxResult<AccessToken> ajaxResult = await JsonSerializer.DeserializeAsync<AjaxResult<AccessToken>>(responseStream);

                if (ajaxResult.Success)
                {
                    _logger.LogDebug("取得token成功");
                    await _cache.SetStringAsync(key, ajaxResult.Data.ToJson());
                    return ajaxResult.Data;
                }
                else
                {
                    _logger.LogError("取得token失败");
                    throw new Exception(ajaxResult.Msg);
                }
            }
            catch (Exception ex)
            {
                //执行成功,记录日志
                msg = string.Format("取得token【异常】[{0}]", ex.Message);
                _logger.LogError(msg);
                throw;
            }
        }

        public async Task<HttpClient> CreateClient()
        {
            var token = (await _cache.GetStringAsync(key)).ToEntity<AccessToken>();
            if (token == null || (token.Expires < DateTime.Now.JsGetTime()))
            {
                token = await GetAccessToken();
            }
            var client = _clientFactory.CreateClient();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Token);
            return client;
        }

        /// <summary>
        /// 发送http的Post请求
        /// </summary>
        /// <param name="input">输入参数和地址</param>
        /// <returns></returns>
        public async Task<string> GetPostData(PostInputDTO input)
        {
            string res = "";
            HttpClient client = await CreateClient();

            //请求网址
            client.BaseAddress = new Uri(input.BaseAddress);
            //参数（json字符串传参）
            HttpContent content = new StringContent(input.JsonData);
            //设置请求头类型为json
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            //请求Api接口地址
            var result = client.PostAsync(input.APISite, content).Result;
            //请求成功后获取参数
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                string resultContent = result.Content.ReadAsStringAsync().Result;
                Console.WriteLine(resultContent);

                res = resultContent;
            }


            return res;
        }

        /// <summary>
        /// 发送http的Post请求
        /// </summary>
        /// <param name="input">输入参数和地址</param>
        /// <returns></returns>
        public string GetTPostData(PostInputDTO input)
        {
          string res = "";
          using (var client = new HttpClient())
          {

            //请求网址
            client.BaseAddress = new Uri(input.BaseAddress);
            //参数（json字符串传参）
            HttpContent content = new StringContent(input.JsonData);
            //设置请求头类型为json
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            //请求Api接口地址
            var result = client.PostAsync(input.APISite, content).Result;
            //请求成功后获取参数
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
              string resultContent = result.Content.ReadAsStringAsync().Result;
              Console.WriteLine(resultContent);

              res = resultContent;
            }

          }
          return res;
        }

        /// <summary>
        /// Post转发文件保存
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<string> SaveHeadImg(PostFileInputDTO input)
        {
            string res = "";
            HttpClient client = await CreateClient();

            //请求网址
            client.BaseAddress = new Uri(input.BaseAddress);
            var content = new MultipartFormDataContent();
            //添加文件参数，参数名为files，文件名为123.png
            content.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(input.FilePath)), "file", input.FileName);
            //请求Api接口地址
            var result = client.PostAsync(input.APISite, content).Result;
            //请求成功后获取参数
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                string resultContent = result.Content.ReadAsStringAsync().Result;
                Console.WriteLine(resultContent);

                res = resultContent;
            }

            return res;
        }

    }


    /// <summary>
    /// AccessToken
    /// </summary>
    public class AccessToken
    {
        /// <summary>
        /// Token
        /// </summary>
        public string Token { get; set; }

        /// <summary>
        /// 过期时间
        /// </summary>
        public long Expires { get; set; }
    }

    public class PostResDTO
    {
        public bool Success { set; get; } = true;

        public string Data { set; get; }

    }

    public class PostFileInputDTO
    {
        /// <summary>
        /// 网站地址
        /// </summary>
        public string BaseAddress { set; get; }

        /// <summary>
        /// 文件路径
        /// </summary>
        public string FilePath { set; get; }

        /// <summary>
        /// 文件名称
        /// </summary>
        public string FileName { set; get; }

        /// <summary>
        /// Api接口地址
        /// </summary>
        public string APISite { set; get; }
    }

    public class PostInputDTO
    {
        /// <summary>
        /// 网站地址
        /// </summary>
        public string BaseAddress { set; get; }

        /// <summary>
        /// 数据
        /// </summary>
        public string JsonData { set; get; }

        /// <summary>
        /// Api接口地址
        /// </summary>
        public string APISite { set; get; }

    }

    public class TheResultDTO
    {
        public string Data { get; set; }
        public int ErrCode { get; set; }
        public string Msg { get; set; }
        public bool Success { get; set; }
    }
}
